<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { getCallListApi } from '@/api/base'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { CallType } from '@/api/base/types'
import { addCallApi, putCallApi } from '@/api/base'
import { ElButton } from 'element-plus'

const ids = ref<string[] | number[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getCallListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data,
      total: res.count
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    fixed: true,
    type: 'selection',
    width: 80,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'index',
    label: t('common.index'),
    type: 'index',
    width: 80,
    fixed: true,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'config.name',
    label: '接口',
    minWidth: 130,
    fixed: true
  },
  {
    field: 'config.request.url',
    minWidth: 240,
    label: '请求地址',
    search: {
      hidden: true
    }
  },
  {
    field: 'config.request.method',
    minWidth: 80,
    label: '请求方法',
    search: {
      hidden: true
    }
  },
  {
    field: 'params',
    minWidth: 200,
    label: '请求参数',
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data) => JSON.stringify(data.row.params)
      }
    }
  },
  {
    field: 'response_body',
    minWidth: 200,
    label: '返回值',
    search: {
      hidden: true
    }
  },
  {
    field: 'process_time',
    label: '处理时间',
    minWidth: 160,
    search: {
      hidden: true
    }
  },
  {
    field: 'create_datetime.$date',
    label: '创建时间',
    minWidth: 180,
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<CallType | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('common.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const action = (row: CallType, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'common.edit' : 'common.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      const res =
        actionType.value === 'add' ? await addCallApi(formData) : await putCallApi(formData)
      if (res) {
        console.log('res', res)
        dialogVisible.value = false
        getList()
      }
    } finally {
      saveLoading.value = false
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction">{{ t('common.add') }}</ElButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      :fit="true"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="700px" max-height="340px">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :current-row="currentRow"
      :form-schema="allSchemas.formSchema"
    />
    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('common.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
</template>
